package cn.kxx.serviceImpl;


import cn.kxx.constant.RedisConstant;
import cn.kxx.entity.PageResult;
import cn.kxx.entity.QueryPageBean;
import cn.kxx.mapper.CheckGroupAndItemMapper;
import cn.kxx.mapper.CheckItemMapper;
import cn.kxx.exception.BusinessException;
import cn.kxx.pojo.CheckGroupAndItem;
import cn.kxx.pojo.CheckItem;
import cn.kxx.service.CheckItemService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.dubbo.config.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import java.util.List;



@Service
public class CheckItemServiceImpl implements CheckItemService {

    Logger logger = LoggerFactory.getLogger(CheckItemServiceImpl.class);


    @Autowired
    private CheckItemMapper checkItemMapper;
    @Autowired
    private CheckGroupAndItemMapper checkGroupAndItemMapper;
//    查询所有检查项
//    引入redistemplate
    @Autowired
    RedisTemplate redisTemplate = new RedisTemplate();

    /**
     * 判断检查项编码是否存在
     *
     * @param code 检查项编码
     */
    private boolean checkCode(String code) {
        LambdaQueryWrapper<CheckItem> queryWrapper =
                new LambdaQueryWrapper<CheckItem>().eq(CheckItem::getCode, code);
        Integer count = checkItemMapper.selectCount(queryWrapper);
        return count > 0;
    }

    /**
     * 判断检查项名称是否存在
     *
     * @param name 检查项名称
     */
    private boolean checkName(String name) {
        LambdaQueryWrapper<CheckItem> queryWrapper =
                new LambdaQueryWrapper<CheckItem>().eq(CheckItem::getName, name);
        Integer count = checkItemMapper.selectCount(queryWrapper);
        return count > 0;
    }


    //        分页查询
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) throws BusinessException {
        Page<CheckItem> page = new Page<>(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        LambdaQueryWrapper queryWrapper = null;
        String queryString = queryPageBean.getQueryString();
        if (!StringUtils.isEmpty(queryString)) {
            queryWrapper = new LambdaQueryWrapper<CheckItem>().like(CheckItem::getName, queryString).or()
                    .eq(CheckItem::getCode, queryString);
        }

        IPage iPage = checkItemMapper.selectPage(page, queryWrapper);

        return new PageResult(iPage.getTotal(), iPage.getRecords());
    }

    @Override
    public void add(CheckItem checkItem) throws BusinessException {

        String key = RedisConstant.QUERY_CHECKITEMS_KEY;
        if (redisTemplate.hasKey(key)){
            redisTemplate.delete(key);
        }
        if (checkItem == null || StringUtils.isEmpty(checkItem.getCode())
                || StringUtils.isEmpty(checkItem.getName())) {
            throw new BusinessException("检查项必要参数为空");
        }
        //判断code和name是否存在
        if (checkCode(checkItem.getCode()) || checkName(checkItem.getName())) {
            throw new BusinessException("编码或名称已经存在");
        }
        checkItemMapper.insert(checkItem);
    }

//    删除单个检查项
    @Override
    public void deleteById(Integer id) throws BusinessException {
        String key = RedisConstant.QUERY_CHECKITEMS_KEY;
        if (redisTemplate.hasKey(key)){
            redisTemplate.delete(key);
        }
//        查看当前id数据库是否有关联

        LambdaQueryWrapper<CheckGroupAndItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CheckGroupAndItem::getCheckitemId, id);
        Integer count = checkGroupAndItemMapper.selectCount(queryWrapper);
        System.out.println(count);
        if (count > 0) {
            throw new BusinessException("检查项被引用，不能删除");
        } else {
            checkItemMapper.deleteById(id);

        }

    }

//    查询单个检查项
    @Override
    public CheckItem findById(Integer id) throws BusinessException {

        String key = RedisConstant.QUERY_CHECKITEMS_KEY;
        if (redisTemplate.hasKey(key)){
            List<CheckItem> list = (List<CheckItem>) redisTemplate.opsForValue().get(key);
            for (CheckItem checkItem : list) {
                if (id == checkItem.getId()){
                    return checkItem;
                }

            }
        }else {
            CheckItem item = checkItemMapper.selectById(id);
            return item;
        }
        CheckItem checkItem = checkItemMapper.selectById(id);
        return checkItem;
    }

//    修改单个检查项
    @Override
    public void edit(CheckItem checkItem) throws BusinessException {
        String key = RedisConstant.QUERY_CHECKITEMS_KEY;
        if (redisTemplate.hasKey(key)){
            redisTemplate.delete(key);
        }
        CheckItem item = checkItemMapper.selectById(checkItem.getId());
        String code = item.getCode();
        String name = item.getName();
        if( (!code.equals(checkItem.getCode())&&checkCode(checkItem.getCode())) ||  (!name.equals(checkItem.getName())&&checkName(checkItem.getName()))){
            throw new BusinessException("编码或名称已经存在");

        }else {
            checkItemMapper.updateById(checkItem);
        }
    }

    @Override
    public List<CheckItem> findAll() {
        List<CheckItem> list = null;
        String key = RedisConstant.QUERY_CHECKITEMS_KEY;
        if (redisTemplate.hasKey(key)){
         logger.info("++++++++缓存中命中");

          list = (List<CheckItem>) redisTemplate.opsForValue().get(key);

          return list;
        }else {

            logger.info("++++++++数据库中命中");
            List<CheckItem> list1 = checkItemMapper.selectList(null);
            redisTemplate.opsForValue().set(key,list1);
            return list1;
        }
    }
}

